#include <iostream>
#include <string>
#include <signal.h>
#include "../comm/httplib.h"
#include "oj_control.hpp"

const std::string wwwroot="./wwwroot";

ns_control::Control* ctl=nullptr;

void handler(int sig)
{
    ctl->RecoveryMachine();
}

int main()
{
    signal(SIGQUIT,handler);

    httplib::Server svr;
    ns_control::Control ctrl;
    ctl=&ctrl;

    /*获取所有题目列表*/
    svr.Get("/all_questions",[&](const httplib::Request& req,httplib::Response& resp){
        // resp.set_content("hello world!!\n","text/plain;charset=utf-8");
        std::string html;
        ctrl.AllQuestions(&html);
        resp.set_content(html,"text/html;charset=utf-8");
    });
    /*用户要根据题目编号，获取题目完整内容*/
    svr.Get(R"(/question/(\d+))",[&](const httplib::Request& req,httplib::Response& resp){
        // resp.set_content("hello world!!\n","text/plain;charset=utf-8");
        std::string number=req.matches[1];
        std::string html;
        ctrl.Question(number,&html);
        resp.set_content(html,"text/html;charset=utf-8");
    });
    svr.Post(R"(/judge/(\d+))",[&](const httplib::Request& req,httplib::Response& resp){
        std::string number=req.matches[1];
        std::string result_json;
        ctrl.Judge(number,req.body,&result_json);
        resp.set_content(result_json,"application/json;charset=utf-8");
    });
    svr.set_base_dir(wwwroot.c_str());//设置wwwroot根目录
    svr.listen("0.0.0.0",8080);
    return 0;
}